<?php
declare (strict_types = 1);

namespace app\mobile\controller;

use think\facade\Request;
use think\facade\Db;
use think\facade\Cache;
use \app\common\Time;
class Login extends \app\mobile\Base
{
  public function loginInfo()
  {
    $base = getSettingGroup('base');
    $info = array();
    $mini = getSettingType('公众号');
    $info['login_color'] = $base['login_color'];
    $info['login_bg'] = $base['login_bg'];
    $info['app_name'] = $base['app_name'];
    $info['mp_app_id'] = $mini['mp_app_id'];
    return $this->doSuccess('ok',$info);
  }

  public function mobileLogin()
  {
    $code = input('code');
    $mobile = input('mobile');
    $invite = input('invite');
    $scene = input('scene');
    if (!$invite && $scene) {
      $scene = str_replace("Z","=",$scene);
      parse_str($scene,$query);
      $invite = $query['invite'];
    }
    
    if (!is_mobile($mobile)) {
      return $this->doError('手机号码不正确');
    }
    $gcode = Cache::get($mobile.'_code');
    if ($gcode != $code) {
      return $this->doError('验证码错误');
    }

    $user = Db::name('user')->where('mobile',$mobile)->find();
    
    if ($user) {
      if ($user['status'] <= 0) {
        return $this->doError('该账户被禁用');
      }
      $log = array();
      $dutime = Time::daysAgo(7);
      if ($user['token_time'] < $dutime) {
        $log['token'] = md5(time().rand(1111,99999999));
      }else{
        $log['token'] = $user['token'];
      }
      $log['last_time'] = $user['login_time'];
      $log['last_ip'] = $user['login_ip'];
      $log['logins'] = $user['logins']+1;
      $log['utime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      Db::name('User')->where('id',$user['id'])->update($log);
      $user['token_time'] = $log['token_time'];
      $user['token'] = $log['token'];
      $user['stime_txt'] = toDatetime($user['stime']);
      $user['etime_txt'] = toDatetime($user['etime']);
      return $this->doSuccess('登陆成功',$user);
    }else{
      $log = array();
      if ($invite) {
        $puser = Db::name('User')->where('id',$invite)->find();
        if ($puser) {
          $log['pid'] = $puser['id'];
        }
      }
      $log['mobile'] = $mobile;
      $log['utime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $dutime = Time::daysAgo(7);
      $log['token'] = md5(time().rand(111,889999999));
      $log['stime'] = time();
      $log['utime'] = time();
      $log['logins'] = 1;
      $log['ctime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      Db::name('User')->insert($log);
      $user = Db::name('user')->where('mobile',$mobile)->find();
      return $this->doSuccess('登陆成功',$user);
    }
    
  }

  public function getMobileCode()
  {
    $mobile = input('mobile');
    if (!is_mobile($mobile)) {
      return $this->doError('手机号码不正确');
    }
    $code = rand(1000,9999);
    Cache::set($mobile.'_code',$code,90);
    return $this->doSuccess('ok',$code);
  }

  public function codeLogin()
  {
    $invite = input('invite');
    $code = input('code');
    $app = \EasyWeChat\Factory::officialAccount(mpcfg());
    // $app = Factory::officialAccount(mpcfg());
    $oauth = $app->oauth;
    $user = $oauth->user()->toArray();
    $openid = $user['id'];
    $scene = input('scene');
    $appPlatform = input('appPlatform');
    $unionid = '';
    if (isset($user['original']['unionid'])) {
      $unionid = $user['original']['unionid'];
    }
    if (!$invite && $scene) {
      $scene = str_replace("Z","=",$scene);
      parse_str($scene,$query);
      if (isset($query['invite'])) $invite = $query['invite'];
    }

    $ck = Db::name('user')
              ->where('openid',$openid)
              ->find();
    if (!$ck && $unionid) {
      $ck = Db::name('User')
            ->where('unionid',$unionid)
            ->find();
    }

    if ($ck) {
      if ($ck['status'] <= 0) {
        return $this->doError('被限制登录');
      }
      $log = array();
      $log['utime'] = time();
      $log['stime'] = time();
      $log['logins'] = $ck['logins']+1;
      $log['last_time'] = $ck['login_time'];
      $log['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      $log['unionid'] = $unionid;
      $log['token'] = $openid;
      $log['openid'] = $openid;
      $log['head'] = $user['avatar'];
      $log['nick'] = $user['nickname'];
      Db::name('User')->where('id',$ck['id'])->update($log);

      return $this->doSuccess('ok',[
        'token'=>$log['token'],
        'id'=>$ck['id'],
      ]);
    }else{
      $log = array();

      $log['utime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['token'] = $openid;
      $log['stime'] = time();
      $log['utime'] = time();
      $log['logins'] = 1;
      $log['ctime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      $log['unionid'] = $unionid;
      $log['openid'] = $openid;
      $log['sex'] = $user['gender']=1?'男':'女';
      $log['head'] = $user['avatar'];
      $log['nick'] = $user['nickname'];
      $log['province'] = $user['original']['province'];
      $log['city'] = $user['original']['city'];
      $pk = Db::name('User')
                // ->fetchSql(true)
                ->insertGetId($log);
      // $user = Db::name('user')->where('id',$pk)->find();
      return $this->doSuccess('ok',[
        'token'=>$log['token'],
        'id'=>$pk,
      ]);
    }
    
    return $this->doSuccess('登陆成功',$user);

  }


  public function openIdLogin()
  {
    //user_bind  先判断绑定帐号是否存在
    $code = input('code');
    $appid = input('appId');
    $head = input('avatarUrl');
    $country = input('country');
    $province = input('province');
    $city = input('city');
    $nick = input('nickName');
    $sex = input('gender');
    $scene = input('scene');
    $encryptedData = input('encryptedData');
    $iv = input('iv');
    $iv = urldecode($iv);
    $encryptedData = urldecode($encryptedData);

    $appPlatform = input('appPlatform');

    $invite = input('invite');
    if (!$invite && $scene) {
      $scene = str_replace("Z","=",$scene);
      parse_str($scene,$query);
      if (isset($query['invite'])) $invite = $query['invite'];
    }

    $user = array();
    $user['appid'] = $appid;
    $user['nick'] = $nick;
    $user['province'] = $province;
    $user['city'] = $city;
    $user['sex'] = $sex;
    $user['head'] = $head;
    

    $app = \EasyWeChat\Factory::miniProgram(minicfg());
    $session = $app->auth->session($code);
    $openid = $session['openid'];
    $userData = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
    
    $unionid = '';
    if (isset($userData['unionId'])) {
      $unionid = $userData['unionId'];
    }

    $ck = Db::name('user')
              // ->where('appid',$appid)
              ->where('openid',$openid)
              ->find();
    if (!$ck && $unionid) {
      $ck = Db::name('User')
            ->where('unionid',$unionid)
            ->find();
    }
    if (!$ck) {
      if ($invite) {
        $puser = Db::name('User')->where('id',$invite)->find();
        if ($puser) {
          $user['pid'] = $puser['id'];
        }
      }
      // $user['type'] = '师傅';
      $user['unionid'] = $unionid;
      $user['token'] = $openid;
      $user['openid'] = $openid;
      $user['type'] = '师傅';
      $user['utime'] = time();
      $user['stime'] = time();
      $user['logins'] = 1;
      $user['login_time'] = time();
      $user['last_time'] = time();
      $user['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      $user['last_ip'] =  $_SERVER["REMOTE_ADDR"];
      $user['token_time'] = time();
      $user['ctime'] = time();
      $uid = Db::name('user')->insertGetId($user);

      unset($user['type']);
      $user['uid'] = $uid;
      $user['openid'] = $openid;
      $c = Db::name('user_bind')->where('openid',$openid)->find();
      if (!$c) {
        Db::name('user_bind')
              ->insertGetId($user);
      }
      
      $user['id'] = $uid;
      return $this->doSuccess('ok',[
        'token'=>$openid,
        'id'=>$uid,
      ]);
    }else{
      if ($ck['status'] <= 0) {
        return $this->doError('被限制登录');
      }
      // $ckuser = Db::name('user')
      //         ->where('id',$ck['uid'])
      //         ->find();
      // if (!$ckuser['status']) {
      //   return $this->doError('被限制登录');
      // }
      $user['openid'] = $openid;
      $user['unionid'] = $unionid;
      $user['login_time'] = time();
      $user['logins'] = $ck['logins']+1;
      $user['login_ip'] =  $_SERVER["REMOTE_ADDR"];
      $user['last_ip'] =  $ck['login_ip'];
      $user['last_time'] = $ck['login_time'];
      $user['token_time'] = time();
      Db::name('user')
              ->where('id',$ck['id'])
              ->update($user);
      return $this->doSuccess('ok',[
        'token'=>$ck['token'],
        'id'=>$ck['id'],
      ]);
    }
  }

}
